<template>
  <!-- 协同审批 - 创建退租流程第一步 -->
  <div class="firstStepPage">
    <div class="contentBox">
      <div class="leftBox">
        <div
            ref="previewBoxRef"
            id="demoDocContainer"
            class="previewBox"
            v-html="state.ctx"></div>
      </div>
      <div
        class="rightBox"
        :class="
          rightBoxState.hideRightBoxFlag ? 'hideRightWidth' : 'showRightWidth'
        "
      >
        <div
          class="ctrlBtnBox"
          :class="rightBoxState.hideRightBoxFlag ? 'toLeftBtn' : 'toRightBtn'"
          @click="doControlRight"
        >
          <el-icon :size="20" v-if="!rightBoxState.hideRightBoxFlag"
            ><ArrowRight
          /></el-icon>
          <el-icon :size="20" v-else><ArrowLeft /></el-icon>
        </div>
        <div
          class="formHeadBox"
          :style="
            rightBoxState.hideRightBoxFlag && rightBoxState.hideRightCnFlag
              ? 'display:none'
              : !rightBoxState.hideRightBoxFlag && rightBoxState.hideRightCnFlag
              ? 'display:none'
              : ''
          "
        >
          固定参数设置
        </div>
        <el-form
          :model="infoForm"
          label-width="130px"
          ref="infoFormRef"
          :rules="formRules.rules"
          :style="
            rightBoxState.hideRightBoxFlag && rightBoxState.hideRightCnFlag
              ? 'display:none'
              : !rightBoxState.hideRightBoxFlag && rightBoxState.hideRightCnFlag
              ? 'display:none'
              : ''
          "
        >
          <el-form-item
            class="limitInput"
            label="解约时间"
            prop="contractBreakTime"
          >
            <el-date-picker
              v-model="infoForm.contractBreakTime"
              style="width: 232px"
              type="date"
              placeholder="请选择日期"
              size="large"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            class="limitInput"
            label="已缴纳租金至"
            prop="rentBreakTime"
          >
            <el-date-picker
              v-model="infoForm.rentBreakTime"
              style="width: 232px"
              type="date"
              placeholder="请选择日期"
              size="large"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="退还押金金额" prop="deposit">
            <el-input
              v-model="infoForm.deposit"
              style="width: 232px"
              placeholder="请输入金额（单位：元）"
              clearable
              @input="
                infoForm.deposit = limitInputNum(infoForm.deposit, 9, 2, true)
              "
            />
          </el-form-item>

          <el-form-item label="户名" prop="bankAccountName">
            <el-input
              v-model="infoForm.bankAccountName"
              style="width: 232px"
              placeholder="点击选择户名"
              readonly
              @click="showAccountSelectDialog"
            />
          </el-form-item>
          <el-form-item label="开户行" prop="bankName">
            <el-input
              v-model="infoForm.bankName"
              style="width: 232px"
              placeholder="所选户名的开户行名称"
              disabled
            />
          </el-form-item>
          <el-form-item label="银行账号" prop="bankAccountNumber">
            <el-input
              v-model="infoForm.bankAccountNumber"
              style="width: 232px"
              placeholder="所选户名的银行账号"
              disabled
            />
          </el-form-item>
          <el-form-item label="补充协议">
              <FileMinioUpload
                      :restriction="true"
                      :restrictionLimit="9"
                      v-model:files="infoForm.fileVoList"
              />
          </el-form-item>
          <el-form-item style="margin-top: 28px">
            <el-button
              color="#FF7B50"
              style="color: #fff"
              type="primary"
              @click="goNext"
              >保存并下一步</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 选择账户弹窗 -->
    <el-dialog
      title="选择账户"
      v-model="dialogVisibleFlag"
      width="900px"
      class="accountDialogBox"
      center
      :close-on-click-modal="false"
    >
      <el-table :data="accountTableData" border>
        <el-table-column type="index" label="序号" width="65" align="center" />
        <el-table-column prop="bankAccountName" label="户名" align="center" />
        <el-table-column prop="bankName" label="开户行" align="center" />
        <el-table-column
          prop="bankAccountNumber"
          label="银行账号"
          align="center"
        />
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template #default="scope">
            <el-button plain color="#FF7B50" @click="selectAccount(scope.row)"
              >选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import {nextTick, onMounted, reactive, ref, watch} from "vue";
import { useRouter } from "vue-router";
import {
    ElForm,
    ElFormItem,
    ElDatePicker,
    ElDialog, ElLoading, ElMessage,
} from "element-plus";
import { ArrowRight, ArrowLeft } from "@element-plus/icons-vue";
import {limitInputNum, localSet, blobToFile} from "@/common/utils/GlobalUtils";
import { thorwLeaseApi } from "@/api/coordination";
import store from "@/store";
import FileMinioUpload from "@/components/FileMinioUpload.vue";


import {reserveInvestmentProjectLibraryApi} from "@/api/investment";
import {renderAsync} from "docx-preview";
//导入PDFObject
import PDFObject from 'pdfobject';

// 从路由path中获取的
const router = useRouter();
let getContractId = router.currentRoute.value.params.contractId;

// form相关
const infoFormRef = ref(null);
const infoForm = reactive({
  contractBreakTime: "",
  rentBreakTime: "",
  deposit: "",
  bankName: "",
  bankAccountName: "",
  bankAccountNumber: "",
  fileVoList:[]
});
// 校验
const formRules = reactive({
  rules: {
    contractBreakTime: [
      { required: true, trigger: "change", message: "请选择解约时间" },
    ],
    rentBreakTime: [
      { required: true, trigger: "change", message: "请选择租金缴纳截止时间" },
    ],
    deposit: [{ required: true, trigger: "blur", message: "请输入押金" }],
    bankAccountName: [
      { required: true, trigger: "blur", message: "请选择户名" },
    ],
  },
});

// 收起/展开 相关
const rightBoxState = reactive({
  hideRightBoxFlag: false, // 控制右侧整体
  hideRightCnFlag: false, // 控制右侧内容部分
});
// 收起/展开按钮点击
const doControlRight = () => {
  rightBoxState.hideRightBoxFlag = !rightBoxState.hideRightBoxFlag;
  if (rightBoxState.hideRightBoxFlag) {
    // 收起时
    setTimeout(() => {
      // 延时控制，解决收起时横向滚动条闪现问题
      rightBoxState.hideRightCnFlag = true;
    }, 200);
  } else {
    // 展开时
    setTimeout(() => {
      // 延时控制，解决展开时横向滚动条闪现问题
      rightBoxState.hideRightCnFlag = false;
    }, 200);
  }
};

// const bankAccountOptionsArr = ref([]);
// 选择账户弹窗相关
const dialogVisibleFlag = ref(false);
const accountTableData = ref([]);
// 获取客户账号信息
const getCustomerBank = () => {
  thorwLeaseApi.getCustomerBank(getContractId).then((res) => {
    const { code, data, msg } = res;
    if (code === '200') {
      accountTableData.value = data;
    }
  });
};
const showAccountSelectDialog = async () => {
  await getCustomerBank();
  dialogVisibleFlag.value = true;
};
const selectAccount = (row) => {
  infoForm.bankName = row.bankName;
  infoForm.bankAccountName = row.bankAccountName;
  infoForm.bankAccountNumber = row.bankAccountNumber;
  dialogVisibleFlag.value = false;
};

// 定义向父组件传值方法
const emits = defineEmits(["nextStep"]);

const state = reactive({
  ctx: "",
});
const initWordInfo = () => {
  thorwLeaseApi.getRentOutWord(getContractId).then((res) => {
    state.ctx = res;
  });
};

// 下一步
const goNext = () => {
  let params = {
    ...infoForm,
    contractId: getContractId,
    rentOutId:getRentOutId
  };
  infoFormRef.value.validate((vaild) => {
    if (vaild) {
      thorwLeaseApi.saveBindData(params).then((res) => {
        const { code, data, msg } = res;
        if (code === '200') {
          store.commit("tuiZuForm", infoForm);
          // 返回退租编号 - rentOutId
          localSet("RentOutId", data);
          // 保存表单信息，从第二步返回时调用
          localSet("ThrowLeaseFirstFormObj", infoForm);
          // 步骤条跳转
          // emits("nextStep", "GoEdit");
          emits("nextStep", "GoSubmit");
        }
      });
    }
  });
};

/**
 * 从vuex中取出数据填充表单
 */
const initForm = () => {
    if (store.state.collaborativeApproval.tuiZuForm) {
        for (let key in store.state.collaborativeApproval.tuiZuForm) {
            for (let key2 in infoForm) {
                infoForm[key] = store.state.collaborativeApproval.tuiZuForm[key];
            }
        }

    }
};

const getRentOutId = router.currentRoute.value.params.id;


const previewBoxRef = ref(null);

/**
 * 预览文档
 * @param fileName
 * @param res
 *
 */
const previewDocument= (fileName,res) => {
    const addTypeArray = fileName.split(".");
    const addType = addTypeArray[addTypeArray.length - 1]
    let params = {'docx':'docx','pdf':'pdf'};
    if(params[addType]){
        let blob = new Blob([res],{
            type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8'
        });
        // let blob = new Blob([res],{
        //     type: 'application/pdf;charset=UTF-8'
        // });

        if(params[addType]==='docx'){
            nextTick(()=>{
                renderAsync(blob, previewBoxRef.value);
            });
        }
        if(params[addType]==='pdf'){
            // 将blob转换为file
            let file = blobToFile(blob,new Date().getTime(),'application/pdf');
            // 将file转换为dataUrl
            let dataUrl = URL.createObjectURL(file);
            PDFObject.embed(dataUrl, '#demoDocContainer', { width: '100%' });
            setTimeout(()=>{
                URL.revokeObjectURL(dataUrl);
            },1000);
        }

    }
}

/**
 * 通过fileKey获取文件流预览docx文档
 * @param fileUrlKey
 * @param callback
 * @param err_callback
 */
const getWord = (fileUrlKey,callback,err_callback) => {
    reserveInvestmentProjectLibraryApi.getPlanWord({templateUrlKey:fileUrlKey}).then(res=>{
        if(res){
            // templateUrl
            previewDocument(fileUrlKey,res);
            if(callback)callback();
        }
        if(res.code!==undefined && res.code === '200'){
            if(err_callback)err_callback();
        }
    });
}

/**
 * 获取退租详情
 */
const getOutContractDraftVo = () => {
    thorwLeaseApi.getOutContractDraftVo({rentOutId:getRentOutId})
        .then(res=>{
            getContractId = res.data.contractId;
            const loading = ElLoading.service({
                lock: true,
                text: 'loading...',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            getWord(res.data.templateUrlKey,()=>{
                loading.close();
            },()=>{
                ElMessage.error('预览合同失败!')
                loading.close();
            });
        });
}

watch(infoForm,(value)=>{
    store.commit("setTuiZuForm", infoForm);
},{deep:true});

onMounted(() => {
  initForm();
  getOutContractDraftVo();
});
</script>

<style lang="scss" scoped>
.firstStepPage {
  .contentBox {
    display: flex;
    .leftBox {
      flex: 1;
      height: 68vh;
      margin-right: 40px;
      overflow: hidden;
      .previewBox {
        height: 100%;
        border: 1px solid #e3e7f1;
        border-radius: 10px;
        padding: 36px 120px 30px;
        overflow-x: hidden;
        overflow-y: auto;
      }
      .editBox {
        background: red;
      }
    }
    .rightBox {
      // width: 428px;
      border-left: 5px solid $title-sm-color;
      border-radius: 10px;
      padding: 30px 0 30px 40px;
      position: relative;
      .ctrlBtnBox {
        width: 34px;
        height: 86px;
        line-height: 94px;
        text-align: center;
        padding-left: 10px;
        background: url("@/assets/iconImg/arrowbox.png") no-repeat;
        background-size: cover;
        position: absolute;
        top: 290px;
        cursor: pointer;
      }
      .toRightBtn {
        left: -39px;
      }
      .toLeftBtn {
        left: 14px;
      }
      .formHeadBox {
        font-size: 16px;
        font-family: SourceHanSansMedium;
        font-weight: 500;
        color: #1a1a1a;
        margin-bottom: 26px;
      }
    }
    .showRightWidth {
      width: 428px;
      transition: all 0.6s;
    }
    .hideRightWidth {
      width: 0px;
      padding-left: 0;
      border-left: none;
      transition: all 0.6s;
    }
  }
}
</style>
<style lang="scss" scoped>
.firstStepPage {
  .contentBox {
    .rightBox {
      :deep(.el-form) {
        .el-form-item {
          margin-bottom: 21px;
        }
      }
    }
  }
  :deep(.accountDialogBox) {
    .el-dialog__header {
      padding-top: 18px;
      padding-bottom: 0;
      .el-dialog__title {
        font-size: 16px;
        font-weight: 500;
        color: #1a1a1a;
        font-family: SourceHanSansMedium;
      }
    }
    .el-dialog__body {
      padding-top: 25px;
      .el-table .el-table__header-wrapper .el-table__header .el-table__cell {
        padding: 20px 0;
        background: #f7f7fa;
        .cell {
          font-weight: 400;
          color: #4d4d4d;
        }
      }
    }
  }
}
</style>
